import random
import tkinter as tk


class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("Snake Game")
        self.canvas = tk.Canvas(self.master, width=400, height=400)
        self.canvas.pack()
        self.snake = [(20, 20), (20, 21), (20, 22)]
        self.direction = "Right"
        self.food = self.create_food()
        self.master.bind("<KeyPress>", self.change_direction)
        self.update_snake()

    def create_food(self):
        while True:
            x = random.randint(0, 19) * 20
            y = random.randint(0, 19) * 20
            if (x, y) not in self.snake:
                return (x, y)

    def change_direction(self, event):
        if event.keysym in ["Up", "Down", "Left", "Right"]:
            self.direction = event.keysym

    def update_snake(self):
        head_x, head_y = self.snake[0]
        if self.direction == "Up":
            new_head = (head_x, head_y - 1)
        elif self.direction == "Down":
            new_head = (head_x, head_y + 1)
        elif self.direction == "Left":
            new_head = (head_x - 1, head_y)
        elif self.direction == "Right":
            new_head = (head_x + 1, head_y)

        if not (0 <= new_head[0] < 20 and 0 <= new_head[1] < 20) or new_head in self.snake:
            self.game_over()
            return

        self.snake = [new_head] + self.snake
        if new_head == self.food:
            self.food = self.create_food()
        else:
            self.snake.pop()

        self.canvas.delete("all")
        self.canvas.create_rectangle(new_head[0] * 20, new_head[1] * 20, (new_head[0] + 1) * 20, (new_head[1] + 1) * 20,
                                     fill="black")
        for x, y in self.snake[1:]:
            self.canvas.create_rectangle(x * 20, y * 20, (x + 1) * 20, (y + 1) * 20, fill="green")
        self.canvas.create_oval(self.food[0], self.food[1], self.food[0] + 20, self.food[1] + 20, fill="red")
        self.master.after(100, self.update_snake)

    def game_over(self):
        self.canvas.delete("all")
        self.canvas.create_text(200, 200, text="Game Over", font=("Helvetica", 36))


if __name__ == "__main__":
    root = tk.Tk()
    game = SnakeGame(root)
    root.mainloop()
